package com.cloudinnov.controller.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudinnov.aop.SystemLog;
import com.cloudinnov.logic.CustomReportAccessRightLogic;
import com.cloudinnov.logic.CustomReportDimensionLogic;
import com.cloudinnov.logic.CustomReportIndexLogic;
import com.cloudinnov.logic.CustomReportLogic;
import com.cloudinnov.logic.CustomReportTimeLogic;
import com.cloudinnov.logic.RealTimeDataLogic;
import com.cloudinnov.logic.SysIndexTypeLogic;
import com.cloudinnov.logic.impl.CustomReportLogicImpl;
import com.cloudinnov.model.Companies;
import com.cloudinnov.model.CustomReport;
import com.cloudinnov.model.CustomReportAccessRight;
import com.cloudinnov.model.CustomReportDimension;
import com.cloudinnov.model.CustomReportIndex;
import com.cloudinnov.model.CustomReportTime;
import com.cloudinnov.model.Equipments;
import com.cloudinnov.model.PageModel;
import com.cloudinnov.model.SysAreas;
import com.cloudinnov.model.SysIndexType;
import com.cloudinnov.utils.CommonUtils;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.github.pagehelper.Page;

@Controller
@RequestMapping("/webapi/customReport")
public class CustomReportController extends BaseController {
	@Autowired
	private CustomReportLogic customReportLogic;
	@Autowired
	private CustomReportAccessRightLogic customReportAccessRightLogic;
	@Autowired
	private CustomReportDimensionLogic customReportDimensionLogic;
	@Autowired
	private CustomReportIndexLogic customReportIndexLogic;
	@Autowired
	private CustomReportTimeLogic customReportTimeLogic;
	@Autowired
	private RealTimeDataLogic realTimeDataLogic;
	@Autowired
	private SysIndexTypeLogic sysIndexTypeLogic;
	/**
	 * 自定义报表-添加
	 * @param customReport 参数
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "自定义报表", methods = "添加")
	public void save(CustomReport customReport, HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		int result = customReportLogic.save(customReport);// 保存客户报表主表数据
		String areas = customReport.getAreas();// 获取地区维度
		CustomReportDimension customReportDimension = null;
		if (areas != null && result == CommonUtils.SUCCESS_NUM) {
			JSONObject areasJson = JSON.parseObject(areas);
			JSONArray countries = areasJson.getJSONArray("countries");
			JSONArray provinces = areasJson.getJSONArray("provinces");
			JSONArray cities = areasJson.getJSONArray("cities");
			String areasDimension = null;
			if (cities != null && cities.size() > 0) {
				areasDimension = cities.toJSONString();
			} else if (provinces != null && provinces.size() > 0) {
				areasDimension = provinces.toJSONString();
			} else if (countries != null && countries.size() > 0) {
				areasDimension = countries.toJSONString();
			}
			if (areasDimension != null) {
				customReportDimension = new CustomReportDimension();
				customReportDimension.setReportCode(customReport.getCode());
				customReportDimension.setDimensionType("area");
				customReportDimension.setDimension(areasDimension);
				customReportDimensionLogic.save(customReportDimension);// 保存报表地区维度数据
			}
		}
		String industries = customReport.getIndustries();// 获取行业维度
		if (CommonUtils.isNotEmpty(industries) && result == CommonUtils.SUCCESS_NUM) {
			JSONObject industriesJson = JSON.parseObject(industries);
			JSONArray firstIndustries = industriesJson.getJSONArray("industries1");
			JSONArray secondIndustries = industriesJson.getJSONArray("industries2");
			JSONArray threeIndustries = industriesJson.getJSONArray("industries3");
			String industriesDimension = null;
			if (firstIndustries != null && firstIndustries.size() > 0) {
				industriesDimension = firstIndustries.toJSONString();
			} else if (secondIndustries != null && secondIndustries.size() > 0) {
				industriesDimension = secondIndustries.toJSONString();
			} else if (threeIndustries != null && threeIndustries.size() > 0) {
				industriesDimension = threeIndustries.toJSONString();
			}
			if (industriesDimension != null) {
				customReportDimension = new CustomReportDimension();
				customReportDimension.setReportCode(customReport.getCode());
				customReportDimension.setDimensionType("industry");
				customReportDimension.setDimension(industriesDimension);
				customReportDimensionLogic.save(customReportDimension);// 保存报表行业维度数据
			}
		}
		String customers = customReport.getCustomers();// 获取客户维度
		if (CommonUtils.isNotEmpty(customers) && result == CommonUtils.SUCCESS_NUM) {
			JSONArray customersJson = JSON.parseArray(customers);
			if (customersJson != null && customersJson.size() > 0) {
				customReportDimension = new CustomReportDimension();
				customReportDimension.setReportCode(customReport.getCode());
				customReportDimension.setDimensionType("customer");
				customReportDimension.setDimension(customersJson.toJSONString());
				customReportDimensionLogic.save(customReportDimension);// 保存报表客户维度数据
			}
		}
		String equipments = customReport.getEquipments();// 获取设备维度
		if (CommonUtils.isNotEmpty(equipments) && result == CommonUtils.SUCCESS_NUM) {
			JSONArray equipmentsJson = JSON.parseArray(equipments);
			if (equipmentsJson != null && equipmentsJson.size() > 0) {
				customReportDimension = new CustomReportDimension();
				customReportDimension.setReportCode(customReport.getCode());
				customReportDimension.setDimensionType("equipment");
				customReportDimension.setDimension(equipmentsJson.toJSONString());
				customReportDimensionLogic.save(customReportDimension);// 保存报表设备维度数据
			}
		}
		String accessRight = customReport.getAccessRight();// 获取报表权限
		if (CommonUtils.isNotEmpty(accessRight) && result == CommonUtils.SUCCESS_NUM) {
			CustomReportAccessRight accessRightModel = JSON.parseObject(accessRight, CustomReportAccessRight.class);
			accessRightModel.setReportCode(customReport.getCode());
			result = customReportAccessRightLogic.save(accessRightModel);// 保存客户报表权限表数据
		}
		String timeModel = customReport.getTime();// 获取报表时间
		if (CommonUtils.isNotEmpty(timeModel) && result == CommonUtils.SUCCESS_NUM) {
			CustomReportTime customReportTime = JSON.parseObject(customReport.getTime(), CustomReportTime.class);
			customReportTime.setReportCode(customReport.getCode());
			result = customReportTimeLogic.save(customReportTime);// 保存客户报表时间表数据
		}
		if (CommonUtils.isNotEmpty(customReport.getIndexTypes()) && result == CommonUtils.SUCCESS_NUM) {
			CustomReportIndex customReportIndex = null;// 保存报表指标数据
			String[] indexCodes = customReport.getIndexTypes().split(CommonUtils.SPLIT_COMMA);
			for (String indexCode : indexCodes) {
				customReportIndex = new CustomReportIndex();
				customReportIndex.setReportCode(customReport.getCode());
				customReportIndex.setIndexCode(indexCode);
				result = customReportIndexLogic.save(customReportIndex);
			}
		}
		String returnData = null;
		if (result == SUCCESS) {
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().println(returnData);
	}
	/**
	 * 自定义报表-删除
	 * @param customReport 参数
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "自定义报表", methods = "删除")
	public void delete(CustomReport customReport, HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		int result = customReportLogic.delete(customReport);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = returnJsonAllRequest(request, response, map, result, "");
		response.getWriter().println(returnData);
	}
	/**
	 * 自定义报表-修改
	 * @param customReport 参数
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "自定义报表", methods = "修改")
	public void update(CustomReport customReport, HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		int result = customReportLogic.update(customReport);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = null;
		if (result == SUCCESS) {
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().println(returnData);
	}
	/**
	 * 自定义报表-查询
	 * @param customReport 参数
	 * @param index
	 * @param size
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public void list(CustomReport customReport, int index, int size, HttpServletRequest request,
			HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException {
		Page<CustomReport> customReports = null;
		customReports = customReportLogic.selectListPage(index, size, customReport, true);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = "";
		if (customReports != null) {
			map.put("list", customReports);
			map.put("total", customReports.getTotal());
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().print(returnData);
	}
	/**
	 * 自定义报表-查询
	 * @param customReport 参数
	 * @param index
	 * @param size
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping(value = "/search", method = RequestMethod.POST)
	@ResponseBody
	public void search(CustomReport customReport, String key, PageModel page, HttpServletRequest request,
			HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException {
		Page<CustomReport> customReports = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("key", key);
		params.put("language", customReport.getLanguage());
		params.put("reportType", customReport.getReportType());
		customReports = customReportLogic.search(page, params);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = "";
		if (customReports != null) {
			map.put("list", customReports);
			map.put("total", customReports.getTotal());
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().print(returnData);
	}
	/**
	 * 查询报表详情
	 * @Title: select
	 * @Description: TODO
	 * @param customReport
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 * @return: void
	 */
	@RequestMapping(value = "/select", method = RequestMethod.GET)
	public void select(CustomReport customReport, HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		CustomReport model = null;
		model = customReportLogic.select(customReport);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = "";
		if (customReport != null) {
			CustomReportDimension customReportDimension = new CustomReportDimension();
			customReportDimension.setReportCode(model.getCode());
			customReportDimension.setDimensionType("area");
			CustomReportDimension customReportDimensionModel = customReportDimensionLogic.select(customReportDimension);
			if (customReportDimensionModel != null) {
				String areas = customReportDimensionModel.getDimension();
				model.setAreas(areas);
			}
			customReportDimension.setDimensionType("industry");
			customReportDimensionModel = customReportDimensionLogic.select(customReportDimension);
			if (customReportDimensionModel != null) {
				String industries = customReportDimensionModel.getDimension();
				model.setIndustries(industries);
			}
			customReportDimension.setDimensionType("customer");
			customReportDimensionModel = customReportDimensionLogic.select(customReportDimension);
			if (customReportDimensionModel != null) {
				String customers = customReportDimensionModel.getDimension();
				model.setCustomers(customers);
			}
			customReportDimension.setDimensionType("equipment");
			customReportDimensionModel = customReportDimensionLogic.select(customReportDimension);
			if (customReportDimensionModel != null) {
				String equipments = customReportDimensionModel.getDimension();
				model.setEquipments(JSON.toJSONString(equipments));
			}
			CustomReportAccessRight accessRightModel = new CustomReportAccessRight();
			accessRightModel.setReportCode(model.getCode());
			String accessRight = JSON.toJSONString(customReportAccessRightLogic.select(accessRightModel) != null
					? customReportAccessRightLogic.select(accessRightModel) : "");
			model.setAccessRight(accessRight);
			CustomReportTime customReportTimeModel = new CustomReportTime();
			customReportTimeModel.setReportCode(model.getCode());
			String timeModel = JSON.toJSONString(customReportTimeLogic.select(customReportTimeModel) != null
					? customReportTimeLogic.select(customReportTimeModel) : "");
			model.setTime(timeModel);
			CustomReportIndex customReportIndex = new CustomReportIndex();
			customReportIndex.setReportCode(model.getCode());
			List<CustomReportIndex> customReportIndexs = customReportIndexLogic.selectList(customReportIndex, false);
			String indexTypes = "";
			if (customReportIndexs != null && customReportIndexs.size() > 0) {
				for (CustomReportIndex customReportIndexModel : customReportIndexs) {
					if (indexTypes != "") {
						indexTypes += customReportIndexModel.getIndexCode();
					} else {
						indexTypes = CommonUtils.SPLIT_COMMA + customReportIndexModel.getIndexCode();
					}
				}
			}
			model.setIndexTypes(indexTypes);
			map.put("model", model);
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().print(returnData);
	}
	@RequestMapping(value = "/detailReportStat", method = RequestMethod.GET)
	public void getReportData(CustomReport customReport, HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		double countValue = 0;
		Map<String, Object> params = new HashMap<>();
		Map<String, Object> value = null;
		List<Map<String, Object>> values = new ArrayList<Map<String, Object>>();
		CustomReport model = customReportLogic.select(customReport);
		params.put("language", customReport.getLanguage());
		if (model != null) {
			CustomReportTime customReportTimeModel = new CustomReportTime();// 获取报表开始时间和结束时间
			customReportTimeModel.setReportCode(model.getCode());
			customReportTimeModel = customReportTimeLogic.select(customReportTimeModel);
			if (customReportTimeModel != null) {
				params.put("beginTime", customReportTimeModel.getBeginTime());// 设置开始时间
				params.put("endTime", customReportTimeModel.getEndTime());// 设置结束时间
				params.put("summaryUnit", customReportTimeModel.getSummaryUnit());// 设置汇总单位
			}
			CustomReportIndex customReportIndex = new CustomReportIndex();// 设置报表指标
			customReportIndex.setReportCode(model.getCode());
			customReportIndex.setLanguage(customReport.getLanguage());
			customReportIndex = customReportIndexLogic.select(customReportIndex);
			if (customReportIndex != null) {
				params.put("valueType", customReportIndex.getValueType());
			}
			// 查询维度 默认查询最低级维度
			CustomReportDimension customReportDimension = new CustomReportDimension();
			customReportDimension.setReportCode(model.getCode());
			List<CustomReportDimension> dimensions = customReportDimensionLogic.selectList(customReportDimension,
					false);
			List<Equipments> equipments = null;
			List<Companies> companys = null;
			List<SysAreas> areas = null;
			for (CustomReportDimension dimension : dimensions) {
				if (dimension != null) {
					if (dimension.getDimensionType().equals("equipment")) {
						equipments = JSON.parseArray(dimension.getDimension(), Equipments.class);
					} else if (equipments == null && dimension.getDimensionType().equals("customer")) {
						companys = JSON.parseArray(dimension.getDimension(), Companies.class);
					} else if (companys == null && dimension.getDimensionType().equals("area")) {
						areas = JSON.parseArray(dimension.getDimension(), SysAreas.class);
					}
				}
			}
			if (equipments != null && equipments.size() > 0) {
				params.put("type", 4);
				for (Equipments equipment : equipments) {
					params.put("equipmentCode", equipment.getCode());
					countValue = realTimeDataLogic.selectPieReportTotalDataByCondition(params);
					value = new HashMap<>();
					value.put("code", equipment.getCode());
					value.put("name", equipment.getName());
					value.put("value", countValue);
					values.add(value);
				}
			} else if (companys != null && companys.size() > 0) {
				params.put("type", 3);
				for (Companies company : companys) {
					params.put("customerCode", company.getCode());
					countValue = realTimeDataLogic.selectPieReportTotalDataByCondition(params);
					value = new HashMap<>();
					value.put("code", company.getCode());
					value.put("name", company.getName());
					value.put("value", countValue);
					values.add(value);
				}
			} else if (areas != null && areas.size() > 0) {
				params.put("type", 1);
				for (SysAreas area : areas) {
					params.put("areaId", area.getId());
					countValue = realTimeDataLogic.selectPieReportTotalDataByCondition(params);
					value = new HashMap<>();
					value.put("code", area.getId());
					value.put("name", area.getName());
					value.put("value", countValue);
					values.add(value);
				}
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = "";
		if (model != null) {
			map.put("list", values);
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().print(returnData);
	}
	

	@SuppressWarnings("unused")
	@RequestMapping(value = "/preview", method = RequestMethod.POST)
	public void preview(CustomReport customReport, HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		double countValue = 0;
		Map<String, Object> params = new HashMap<>();
		Map<String, Object> value = null;
		List<Map<String, Object>> values = new ArrayList<Map<String, Object>>();
		String areas = customReport.getAreas();// 获取地区维度
		String industries = customReport.getIndustries();// 获取行业维度
		String customers = customReport.getCustomers();// 获取客户维度
		String equipments = customReport.getEquipments();// 获取设备维度
		List<Equipments> equipmentsList = null;
		List<Companies> companysList = null;
		List<SysAreas> areasList = null;
		if (equipments != null) {
			equipmentsList = JSON.parseArray(equipments, Equipments.class);
		} else if (equipmentsList == null) {
			companysList = JSON.parseArray(customers, Companies.class);
		} else if (companysList == null) {
			areasList = JSON.parseArray(areas, SysAreas.class);
		}
		String accessRight = customReport.getAccessRight();// 获取报表权限
		String timeModel = customReport.getTime();// 获取报表时间
		params.put("language", customReport.getLanguage());
		if (timeModel != null) {
			CustomReportTime customReportTime = JSON.parseObject(customReport.getTime(), CustomReportTime.class);
			params.put("beginTime", customReportTime.getBeginTime());// 设置开始时间
			params.put("endTime", customReportTime.getEndTime());// 设置结束时间
			params.put("summaryUnit", customReportTime.getSummaryUnit());// 设置汇总单位
		}
		if (CommonUtils.isNotEmpty(customReport.getIndexTypes())) {
			SysIndexType sysIndexType = null;// 保存报表指标数据
			String[] indexCodes = customReport.getIndexTypes().split(CommonUtils.SPLIT_COMMA);
			for (String indexCode : indexCodes) {
				sysIndexType = new SysIndexType();
				sysIndexType.setCode(indexCode);
				sysIndexType.setLanguage(customReport.getLanguage());
				sysIndexType = sysIndexTypeLogic.select(sysIndexType);
				if (sysIndexType != null) {
					params.put("valueType", sysIndexType.getValueType());
				}
			}
		}
		if(customReport.getReportType().equals(CustomReportLogicImpl.REPORT_TYPE_PIE)){
			if (equipmentsList != null && equipmentsList.size() > 0) {
				params.put("type", 4);
				for (Equipments equipment : equipmentsList) {
					params.put("equipmentCode", equipment.getCode());
					countValue = realTimeDataLogic.selectPieReportTotalDataByCondition(params);
					value = new HashMap<>();
					value.put("code", equipment.getCode());
					value.put("name", equipment.getName());
					value.put("value", countValue);
					values.add(value);
				}
			} else if (companysList != null && companysList.size() > 0) {
				params.put("type", 3);
				for (Companies company : companysList) {
					params.put("customerCode", company.getCode());
					countValue = realTimeDataLogic.selectPieReportTotalDataByCondition(params);
					value = new HashMap<>();
					value.put("code", company.getCode());
					value.put("name", company.getName());
					value.put("value", countValue);
					values.add(value);
				}
			} else if (areasList != null && areasList.size() > 0) {
				params.put("type", 1);
				for (SysAreas area : areasList) {
					params.put("areaId", area.getId());
					countValue = realTimeDataLogic.selectPieReportTotalDataByCondition(params);
					value = new HashMap<>();
					value.put("code", area.getId());
					value.put("name", area.getName());
					value.put("value", countValue);
					values.add(value);
				}
			}
		}else if(customReport.getReportType().equals(CustomReportLogicImpl.REPORT_TYPE_BAR) || customReport.getReportType().equals(CustomReportLogicImpl.REPORT_TYPE_LINE)){
			if (equipmentsList != null && equipmentsList.size() > 0) {
				params.put("type", 4);
				for (Equipments equipment : equipmentsList) {
					params.put("equipmentCode", equipment.getCode());
					//countValue = realTimeDataLogic.selectReportDataByCondition(params);
					value = new HashMap<>();
					value.put("code", equipment.getCode());
					value.put("name", equipment.getName());
					value.put("value", countValue);
					values.add(value);
				}
			} else if (companysList != null && companysList.size() > 0) {
				params.put("type", 3);
				for (Companies company : companysList) {
					params.put("customerCode", company.getCode());
					countValue = realTimeDataLogic.selectPieReportTotalDataByCondition(params);
					value = new HashMap<>();
					value.put("code", company.getCode());
					value.put("name", company.getName());
					value.put("value", countValue);
					values.add(value);
				}
			} else if (areasList != null && areasList.size() > 0) {
				params.put("type", 1);
				for (SysAreas area : areasList) {
					params.put("areaId", area.getId());
					countValue = realTimeDataLogic.selectPieReportTotalDataByCondition(params);
					value = new HashMap<>();
					value.put("code", area.getId());
					value.put("name", area.getName());
					value.put("value", countValue);
					values.add(value);
				}
			}
		}
		
		
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = "";
		if(values.size()>0){
			map.put("list", values);
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		}else{
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().print(returnData);
	}
}
